package com.codeiy.auth;

import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.codeiy.criteria.CriteriaQuery;
import com.codeiy.dto.R;
import com.codeiy.dto.sys.SysUser;
import com.codeiy.util.DevPlatformUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import static com.codeiy.constant.CommonConstants.TENANT_ID;
import static com.codeiy.constant.CommonConstants.USERNAME;

@RestController
@RequiredArgsConstructor
@RequestMapping("/auth")
public class AuthController {
    private final DevPlatformUtils devPlatformUtils;

    /**
     * 登录
     *
     * @param loginInfo 登录信息
     */
    @PostMapping("/login")
    public Mono<R> login(@RequestBody CriteriaQuery loginInfo) {
        if (!devPlatformUtils.isAlive()) {
            return Mono.just(R.failed("开发平台未启动"));
        }

        return devPlatformUtils.create("/warehouse/get").post().bodyValue(loginInfo).retrieve().bodyToMono(R.class).map(r -> {
            if (!r.isSuccess()) {
                return R.failed(r.getMsg());
            }
            SysUser sysUser = r.getData() == null ? null : JSONUtil.toBean(JSONUtil.toJsonStr(r.getData()), SysUser.class);
            if (sysUser == null || StrUtil.isBlank(sysUser.getUserCode())) {
                return R.failed("用户名或密码错误");
            }
            boolean login = StpUtil.isLogin();
            if (!login) {
                StpUtil.login(sysUser.getUserCode(), SaLoginConfig
                        .setExtra(USERNAME, sysUser.getUserName())
                        .setExtra("avatar", sysUser.getAvatar())
                        .setExtra("email", sysUser.getEmail())
                        .setExtra("phone", sysUser.getPhone())
                        .setExtra(TENANT_ID, sysUser.getTenantId()));
            }
            return R.ok(StpUtil.getTokenValue());
        });
    }
}
